using System;
using System.Collections;
using UnityEditor;
using UnityEngine;
using Object = System.Object;

namespace Games.Frameworks.UIParticle
{
    [ExecuteAlways]
    public class UIParticleHelper:MonoBehaviour
    {
        [SerializeField]private int _id;
        public int Id
        {
            get { return _id;}
            set { _id = value; }
        }

        public Camera myCamera;

        public RenderTexture renderTexture;
        public UIParticle uiParticle;
        public static readonly int helpersDistance = 3000;//模拟的很大的值

        public bool use;//是否时处于播放状态

        public void Awake()
        {
            Init();
        }

        public void Init()
        {
            Id = Id!=0?Id:++UIParticleManager.nowMaxHelperId;
            transform.position=new Vector3(-helpersDistance/2-1,(Id-1)*helpersDistance,0);
            myCamera = GetComponentInChildren<Camera>(true);
            myCamera.backgroundColor=new Color(0,0,0,0); 
        }

        public void Play(UIParticle particle)
        {
            use = true;
            uiParticle = particle;
            //设置摄像机大小
            var height=particle.rawImage.rectTransform.rect.height;
            var width=particle.rawImage.rectTransform.rect.width;
        
            myCamera=myCamera??GetComponentInChildren<Camera>(true);
            myCamera.gameObject.SetActive(true);
            myCamera.orthographicSize = height<width?height/2:width/2;
            myCamera.farClipPlane = height>width?height:width;
            
            //新建RenderTexture
            renderTexture = new RenderTexture((int)width, (int)height,0);
            myCamera.targetTexture = renderTexture;
            
            //设置好RawImage
            particle.rawImage.color=Color.white;
            particle.rawImage.texture = renderTexture;

            //复制粒子系统并播放
            GameObject particleObj;
            if (Application.isPlaying)
            {
                particleObj = particle.Particle.gameObject;
            }
            else
            {
                particleObj = Instantiate(particle.Particle.gameObject);
                particle.Particle.gameObject.SetActive(false);//可能能够节约资源
            }
            particleObj.SetActive(true);
            particleObj.transform.SetParent(transform);
            particleObj.transform.localPosition= new Vector3(0, 0, (height>width?height:width) / 2);
            particleObj.GetComponent<ParticleSystem>().Play();
        }

        //UI粒子停止播放+回收
        public void Stop(bool pause=false)
        {
            //清理粒子系统
            var particleSystem = GetComponentInChildren<ParticleSystem>();
            if (particleSystem != null)
            {
                particleSystem.Stop();
                //是否是回收还是直接销毁
                if (uiParticle != null&&pause)
                {
                    //在回收时，在被修改enable/active时 不能执行SetParent()  所以停了一帧
                    StartCoroutine(LateSetParent(particleSystem,uiParticle));
                }
                else
                {
                    //为了应对一个编辑器直接删除的情况
                    if(Application.isPlaying)
                        Destroy(particleSystem.gameObject);
                    else
                        DestroyImmediate(particleSystem.gameObject);
                }
            }
            
            //清理rawImage
            if (uiParticle != null&&uiParticle.rawImage!= null)
            {
                uiParticle.rawImage.texture = null;
            }
            
            //清理摄像机
            myCamera.targetTexture = null;
            myCamera.gameObject.SetActive(false);
            
            //清理其他
            renderTexture = null;
            
            this.uiParticle = null;
            use = false;
        }
        
        //在回收时，在被修改enable/active时 不能执行SetParent()  所以停了一帧
        IEnumerator LateSetParent(ParticleSystem particleSystem,UIParticle newUIParticle)
        {
            yield return null;
            try
            {
                particleSystem.gameObject.transform.SetParent(newUIParticle.transform);
            }
            catch (MissingReferenceException _)
            {
                Debug.Log(_);
                DestroyImmediate(particleSystem.gameObject);
            }
        }
        
        //编辑粒子完成 将其保存到prefab（原物体）中
        public void EditorComplete()
        {
            var particleSystem = GetComponentInChildren<ParticleSystem>();
            if (particleSystem != null)
            {
                UnityEditorInternal.ComponentUtility.CopyComponent(particleSystem);
                UnityEditorInternal.ComponentUtility.PasteComponentValues(uiParticle.Particle);
                particleSystem.Stop();
                DestroyImmediate(particleSystem.gameObject);
            }
            myCamera.targetTexture = null;
            myCamera.gameObject.SetActive(false);
            renderTexture = null;
            
            this.uiParticle = null;
            use = false;
        }

        //粒子的自动播放 为AutoParticles脚本封装的函数
        private ParticleSystem autoParticle;
        public void AutoSimulate(float time)
        {
            if (autoParticle == null)
                    autoParticle = GetComponentInChildren<ParticleSystem>();
            if (autoParticle != null)
            {
                autoParticle.Simulate(time,true,false);
                myCamera.Render();
            }
        }
        
    }
}

